﻿using System;
using System.Collections.Generic;
using System.Text;
using HttpAssiant.Wrapper;
using System.Net;
using HttpAssiant.Utils;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace HttpAssiant.BLL
{
    public class JFBLL
    {
        private string referer = "";

        private string sid = "";

        string imgPath = System.IO.Directory.GetCurrentDirectory() + "\\img\\";


        /// <summary>
        /// 积分
        /// </summary>
        private int userCurrentIntegral = 0;

        /// <summary>
        /// 记忆的缓存Key
        /// </summary>
        private string memcacheKey = "";

        //受赠人信息
        Model.donee doneeInfo = new HttpAssiant.Model.donee();

        //受赠人逻辑处理
        donee doneeBll = new donee();

        private HttpUtils httpUtils = null;

        private const string LOGINGETURL = "https://jf.10086.cn/login/login.jsp";

        private const string ISUSERLOGIN = "http://jf.10086.cn/asynlogin/user/web/UserLoginAction?action=isUserLogin&time=";

        private const string ISLOGINBEFOR = "http://jf.10086.cn/asynlogin/ngves.asiainfo.portal.user.web.UserLoginAction?action=isLoginBefore";

        private const string IMAGERAND = "http://jf.10086.cn/imageRand";

        private const string LOGIN = "http://jf.10086.cn/asynlogin/ngves.asiainfo.portal.user.web.UserLoginAction?action=login";

        private const string PRODUCTURL = "http://jf.10086.cn/ware/100000004824204.html";

        private const string PRODUCTID = "100000004824204";

        private const string PRO_GETLESSSTORAGE = "http://jf.10086.cn/portal/ware/web/WareDetailAction?action=getLessStorage";

        private const string PRO_GETWAREDESCVALUE = "http://jf.10086.cn/portal/ware/web/WareDetailAction?action=getWareDescValue";

        private const string CHECKUSER = "http://jf.10086.cn/portal/order/web/UserOrderAction?action=checkUserInfo";

        private const string SAVEASSIGNEEINFOS = "http://jf.10086.cn/portal/user/web/UserAccountAction?action=saveAssigneeInfos";

        private const string GETASSIGNEEINFO = "http://jf.10086.cn/portal/user/web/UserAccountAction?action=getAssigneeInfo";

        private const string SENDTRANSFERCONFIRMCODE = "http://jf.10086.cn/portal/ngves.asiainfo.portal.order.web.UserOrderAction?action=sendTranferConfirmCode";

        private const string TRANSFERPOINTS = "http://jf.10086.cn/portal/user/web/UserAccountAction?action=transferPoints";

        private string phone;
        private string pwd;

        /// <summary>
        /// 识别出来的验证码
        /// </summary>
        private string radom = "";


        public JFBLL(string _phone, string _pwd, string _sid)
        {
            phone = _phone;
            pwd = _pwd;
            sid = _sid;
            httpUtils = new HttpUtils(_sid);

            

            doneeInfo = doneeBll.GetModelByRandom();
            if (doneeInfo == null)
            {
                throw new NotImplementedException("获取受赠人信息失败");
            }
        }

        public string Get_LoginUrl()
        {
            return httpUtils.DoGet(LOGINGETURL, null);
        }

        public string Post_IsUserLogin(bool first)
        {
            //检测是否登陆成功， 可以监测积分
            if (first)
            {
                referer = "http://jf.10086.cn/login/login.jsp";
            }
            else
            {
                referer = PRODUCTURL;
            }
            
             
            
            string content = "time=" + HttpUtils.RunJavascript("new Date().getTime().toString(36);");
            string result = httpUtils.DoPost(ISUSERLOGIN, content, referer);


            return result;
        }

        public string Post_ISLOGINBEFOR()
        {
            string content = "mobilePhone="+phone;
            return httpUtils.DoPost(ISLOGINBEFOR, content, referer);
        }

        public bool Down_IMAGERAND()
        { 
            string url = IMAGERAND + "?t="+HttpUtils.RunJavascript("new Date().getTime().toString(36);");
            return httpUtils.Download(url, imgPath, phone + ".jpg", "");
        }

        public string RecognizeRadon()
        {
            string fullPath = imgPath + phone + ".jpg";
            radom = WrapperUtil.getInstance().recognize(fullPath);
            return radom;
        }

        public string Post_LOGIN()
        { 
            WebHeaderCollection headers = new WebHeaderCollection();
            headers.Add("x-requested-with", "XMLHttpRequest");
            string content = "mobilePhone=" + phone ;
            content += "&code=123"+radom;
            content += "&password=" + EncodePwd.encodeForPwd(pwd);
            content += "&isRememberMe=1";
            return httpUtils.DoPost(LOGIN, content, referer, headers);
        }

        public string Get_PRODUCTURL()
        {
            return httpUtils.DoGet(PRODUCTURL,null);
        }

        public string Post_PRO_GETLESSSTORAGE()
        {
            string content = "ware_id=" + PRODUCTID;
            return httpUtils.DoPost(PRO_GETLESSSTORAGE, content, referer);
        }

        public string Post_PRO_GETWAREDESCVALUE()
        {
            string content = "wareIds=" + PRODUCTID;
            return httpUtils.DoPost(PRO_GETWAREDESCVALUE, content, referer);
        }

        public string Post_CHECKUSER()
        {
            //可以获得积分情况
            string content = "";
            return httpUtils.DoPost(CHECKUSER, content, referer);
        }

        public string Post_SAVEASSIGNEEINFOS()
        {
            
            referer = "http://jf.10086.cn/portal/user/web/UserAccountAction?action=addAssigneeInfos";
            string content = "assigneeMobile="+doneeInfo.phone;
            content += "&assigneeName=" + HttpUtility.UrlEncode(doneeInfo.uname, Encoding.UTF8);
            content += "&certificateType=01";
            content += "&certificateNum=" + doneeInfo.ucard;
            return httpUtils.DoPost(SAVEASSIGNEEINFOS, content, referer);
            
        }


        public string Get_GETASSIGNEEINFO()
        {
            return httpUtils.DoGet(GETASSIGNEEINFO, referer);
        }

        public string Post_SENDTRANSFERCONFIRMCODE()
        {
            referer = "http://jf.10086.cn/portal/user/web/UserAccountAction?action=toTransferPoints";
            return httpUtils.DoPost(SENDTRANSFERCONFIRMCODE, "", referer);
        }

        public string Post_TRANSFERPOINTS(string confirmCode, int integer)
        {
            string content = "integer=" + integer.ToString();
            content += "&transferNum="+doneeInfo.phone;
            content += "&confirmCode=" + confirmCode;

            string result = httpUtils.DoPost(TRANSFERPOINTS, content, referer);

            //受赠人添加受赠积分
            doneeInfo.newintegra += integer;
            doneeBll.Update(doneeInfo);

            return result;
        }

        //解析返回的人员信息
        private void AnalizeIsLoginUser(string isLoginUser)
        {
            //{"status":"USER_LOGIN_STATUS_LOGIN","localCount":"N","flagIntegralDetail":true,"sum":"3","info":{"provCode":"ha","mobileBrand":"2","mobileLevel":"100","starLevelName":"","totalPoint":"0","mobileNumber":"15136173912","userCurrentIntegral":"979","loginFailNum":0,"memcacheKey":"f9f2fde67db3d6d62272287f7d49de1a"}}
            JObject userJsonObj = JObject.Parse(isLoginUser);

            if (userJsonObj.Property("info")!=null)
            {
                JObject userInfo = (JObject)userJsonObj["info"];
                userCurrentIntegral = Convert.ToInt32(userInfo["userCurrentIntegral"]);
                memcacheKey = userInfo["memcacheKey"].ToString();
            }
        }
    }

}
